var
    mysql = require("mysql"),
    path = require('path'),
    Sequelize = require('sequelize'),
    fs = require("fs"),
    config = require('../conf/jdbc').config(),
    package = require('../../../package.json'),
    models_path = path.join(__dirname, '..\\..\\..\\routes\\models');
var sequelize = new Sequelize(config.database, config.username, config.password, config.opts);
sequelize.DataTypes = Sequelize;
global.db = module.exports.sequelize = sequelize;
(function a(dir) {
    console.log(dir);
    var models_files = fs.readdirSync(dir);
    for (var i in models_files) {
        var filePath = models_files[i];
        var stat = fs.lstatSync(path.join(dir, filePath));
        if (stat.isDirectory()) {
            a.call(this, path.join(dir, filePath));
        } else if (filePath.endsWith("Model.js")) {
            require(path.join(dir, filePath))(sequelize);
        }
    }
})(models_path);

var promise = new Promise(function (resolve, reject) {
    if (package.isInitTable) {
        sequelize.sync({force: true}).then(function () {
            resolve();
        });
    }
});
promise.then(function () {
    for (var j in sequelize.models) {
        var model = sequelize.models[j];
        console.log(j + " initRelation executing")
        if (model.initRelation) {
            model.initRelation();
            console.log(j + " initRelation completed execution")
        }
    }
    return this;
}).then(function () {
    if (package.isInitTableData) {//数据初始化
        for (var k in sequelize.models) {
            var model = sequelize.models[k];
            if (model.initData) {
                model.bulkCreate(model.initData);
            }
        }
    }
    return this;
});